// https://www.lintcode.com/problem/sqrtx/my-submissions

class Solution {
public:
    /**
     * @param x: An integer
     * @return: The sqrt of x
     */
    int sqrt(int x) {
        long long start = 0;
        // int end = x - 1;
        long long end = x;
        while (start + 1 < end)
        {
            long long mid = (end - start) / 2 + start;
            if (mid * mid < x) start = mid;
            else end = mid;
        }
        if (end * end <= x) return end;
        else return start;
    }
};


// https://leetcode.cn/problems/sqrtx/
class Solution {
public:
    int mySqrt(int x) {
        int l = 0;
        int r = x;
        while (l + 1 < r) {
            int mid = (r - l) / 2 + l;
            // if ((long long)mid * mid == x) return mid;
            // else if ((long long)mid * mid < x) l = mid;
            if (mid == x / mid) return mid; // 可以防止越界
            else if (mid < x / mid) l = mid;
            else r = mid;
        }
        if ((long long)r * r <= x) return r;
        // if (r <= x / r) return r; 除0问题
        else return l;
    }
};